# !/usr/bin/python
# @author: 'yu.qian'
# @datetime: 2022-12-17 15:00

# pip install pyDes
import base64

from pyDes import des, PAD_PKCS5, ECB

SECRET_KEY = [-36, -63, 49, 37, -56, -32, 103, -85]


def des_encrypt(s, to_base64=True):
    """
    DES 加密

    :param s: 原始字符串
    :param to_base64: 是否将结果Base64加密
    :return: 加密后字符串
    """
    if isinstance(s, str):
        s = s.encode('utf-8')
    k = des(SECRET_KEY, ECB, None, pad=None, padmode=PAD_PKCS5)
    result = k.encrypt(s, padmode=PAD_PKCS5)
    return base64.b64encode(result) if to_base64 else result


def des_descrypt(s, from_base64=True):
    """
    DES 解密

    :param s: 加密后的字符串
    :param from_base64: 参数是否经过Base64加密
    :return: 解密后的字符串
    """
    if isinstance(s, str):
        s = s.encode('utf-8')
    k = des(SECRET_KEY, ECB, None, pad=None, padmode=PAD_PKCS5)
    result = k.decrypt(base64.b64decode(s) if from_base64 else s, padmode=PAD_PKCS5)
    return result


if __name__ == '__main__':
    str1 = "qianyu123"
    str2 = des_encrypt(str1)
    print("1:", str2)
    str3 = des_descrypt(str2)
    print("2:", str3)
